package com.onemile.location;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.json.JSONArray;
import org.json.JSONObject;

import com.onemile.entity.Session;
import com.onemile.entity.model.ELocation;

import android.content.Context;
import android.os.AsyncTask;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;

public class NetGPRSLocation extends AsyncTask<Void, Integer, ELocation>
{
   private TaskCallBack mCallBack;
   private TelephonyManager tm;
   private ELocation eLocation;
   private String address = "";

   private int CONNECTION_TIMEOUT = 20000;
   private int SO_TIMEOUT = 20000;

   public NetGPRSLocation(Context context, TaskCallBack callBack)
   {
	  tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
	  mCallBack = callBack;
   }

   void getStation()
   {
	  try
	  {
		 GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
		 eLocation = new ELocation();
		 eLocation.setCid(gcl.getCid());
		 eLocation.setLac(gcl.getLac());
		 eLocation.setMcc(Integer.valueOf(tm.getNetworkOperator().substring(0, 3)));
		 eLocation.setMnc(Integer.valueOf(tm.getNetworkOperator().substring(3, 5)));
		 eLocation.setIMEI(tm.getDeviceId());

		 List<NeighboringCellInfo> infos = tm.getNeighboringCellInfo();
		 for (NeighboringCellInfo info : infos)
		 {
			// 获取邻居小区号
			int cid2 = info.getCid();
			// 获取邻居小区LAC，LAC:
			// 位置区域码。为了确定移动台的位置，每个GSM/PLMN的覆盖区都被划分成许多位置区，LAC则用于标识不同的位置区。
			info.getLac();
			info.getNetworkType();
			info.getPsc();
			// 获取邻居小区信号强度
			info.getRssi();
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "NetGPRSLocation_getStation() ", e);
		 }
	  }
	  try
	  {
		 // 组装JSON查询字符串
		 JSONObject holder = new JSONObject();
		 holder.put("version", "1.1.0");
		 holder.put("host", "maps.google.com");
		 // holder.put("address_language", "zh_CN");
		 holder.put("request_address", true);

		 JSONArray array = new JSONArray();
		 JSONObject data = new JSONObject();
		 data.put("cell_id", eLocation.getCid()); // 25070
		 data.put("location_area_code", eLocation.getLac());// 4474
		 data.put("mobile_country_code", eLocation.getMcc());// 460
		 data.put("mobile_network_code", eLocation.getMnc());// 0
		 array.put(data);
		 holder.put("cell_towers", array);

		 // 创建连接，发送请求并接受回应
		 DefaultHttpClient client = new DefaultHttpClient();

		 client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
		 client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);

		 HttpPost post = new HttpPost("http://www.google.com/loc/json");

		 StringEntity se = new StringEntity(holder.toString());

		 post.setEntity(se);
		 HttpResponse resp = client.execute(post);

		 HttpEntity entity = resp.getEntity();

		 BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
		 StringBuffer sb = new StringBuffer();
		 String result = br.readLine();

		 while (result != null)
		 {
			sb.append(result);
			result = br.readLine();
		 }
		 JSONObject jsonObject = new JSONObject(sb.toString());

		 JSONObject jsonObject1 = new JSONObject(jsonObject.getString("location"));

		 eLocation.setLatitude(jsonObject1.getString("latitude"));
		 eLocation.setLongitude(jsonObject1.getString("longitude"));

		 if(eLocation.getLongitude()==null||eLocation.getLongitude()==null)
		 {
			eLocation=null;
			return;
		 }
		 getAddress(eLocation);
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "NetGPRSLocation_getStation() ", e);
		 }
	  }
   }

   void getAddress(ELocation _modLocation)
   {
	  try
	  {
		 URL url = new URL("http://maps.google.cn/maps/geo?key=abcdefg&q=" + _modLocation.getLatitude() + "," + _modLocation.getLongitude());
		 InputStream inputStream = url.openConnection().getInputStream();
		 InputStreamReader inputReader = new InputStreamReader(inputStream, "utf-8");
		 BufferedReader bufReader = new BufferedReader(inputReader);

		 String line = "", lines = "";

		 while ((line = bufReader.readLine()) != null)
		 {
			lines += line;
		 }
		 if (!lines.equals(""))
		 {
			JSONObject jsonobject = new JSONObject(lines);
			JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark").toString());
			for (int i = 0; i < jsonArray.length(); i++)
			{
			   address = address + jsonArray.getJSONObject(i).getString("address");
			}
			_modLocation.setAddress(address);
		 }

	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "NetGPRSLocation_getAddress(_modLocation) ", e);
		 }
	  }
   }

   @Override
   protected ELocation doInBackground(Void... params)
   {
	  try
	  {
		 getStation();
		 return eLocation;
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "NetGPRSLocation_doInBackground(params) ", e);
		 }
	  }

	  return null;
   }

   @Override
   protected void onPostExecute(ELocation result)
   {
	  try
	  {
		 mCallBack.DoWhenComplete(result);
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "NetGPRSLocation_onPostExecute(result) ", e);
		 }
	  }
   }

   public interface TaskCallBack
   {
	  public void DoWhenComplete(ELocation result);
   }
}
